import {celebrate, Joi} from "celebrate";
import {Request, Router} from "express";
import ms = require("ms");
import {alipayCashier} from "../alipay/payment";
import {ProductModel} from "../database/models/Product";
import {ProductOrderModel} from "../database/models/ProductOrder";
import {wechatPayCashier} from "../wechat/wechatCashier";
import {InternalError} from "./error";
import {Response, withProduct, withUser} from "./middlewareType";
import {jwtAuthMiddleware} from "./passort";

const router = Router()


router.post('/:productId',
  jwtAuthMiddleware,
  celebrate({
      params: Joi.object().keys({productId: Joi.string().required()}),
      body: Joi.object().keys({
        payType: Joi.string().required().valid(["wechatPay", "aliPay"])
      })
    }
  ),
  async (req: Request & withProduct, res: Response, next) => {
    const p = await ProductModel.findOne({_id: req.params.productId, state: 'on'}).lean()

    if (p) {
      if (p.stock > 0) {
        req.product = p
        next()
      } else {
        res.error(InternalError("NO_ON_STOCK"))
      }
    } else {
      res.error(InternalError('NO_SUCH_PRODUCT'))
    }
  },
  async (req: Request & withUser & withProduct, res: Response) => {

    const product = req.product
    // const inviteBy = req.user.inviteBy || null
    const inviteBy = req.user.inviteBy || null

    const po = new ProductOrderModel({
      product,
      productName: product.name,
      productDescription: product.description,
      productCoverUrl: product.coverUrl,
      player: req.user.id,
      state: 'unpaid',
      createAt: new Date(),
      RMBCost: product.marketPrice,
      inviteBy
    })

    await po.save()

    const paymentArg = {
      title: '购买商品',
      detail: product.name,
      price: product.marketPrice,
      order: po.id,
      type: 'ProductOrder',
      fromIP: req.ip
    }

    const cashier = req.body.payType === 'wechatPay' ? wechatPayCashier : alipayCashier

    const payOrder = await cashier.createPaymentOrder(paymentArg, ms('15min'))

    res.json({
      ok: true,
      data: {
        productOrder: po,
        payOrder: payOrder.prepay
      }
    })
  }
)

export default router
